package com.whenjun.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.ifootbook.util.CopyerObject;
import com.ifootbook.util.EmptyUtil;
import com.whenjun.dto.isc.person.IscPersonReq;
import com.whenjun.dto.isc.person.UserReqISC;
import com.whenjun.dto.person.IscPersonDTO;
import com.whenjun.entity.IscPerson;
import com.whenjun.mapper.IscPersonMapper;
import com.whenjun.service.IIscPersonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whenjun.util.ArtemisPostUtil;
import com.whenjun.util.IPageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whenjun
 * @since 2024-01-30
 */
@Service
public class IscPersonServiceImpl extends MPJBaseServiceImpl<IscPersonMapper, IscPerson> implements IIscPersonService {

    @Autowired
    private ArtemisPostUtil artemisPostUtil;

    @Transactional
    public IPage<IscPersonDTO> persons(IscPersonReq iscPersonReq) {
        Page<IscPerson> page = new Page<>(iscPersonReq.getPage(), iscPersonReq.getSize());

        IPage<IscPerson> iscPersonList = this.lambdaQuery()
                .eq((iscPersonReq != null && !EmptyUtil.isEmpty(iscPersonReq.getPersonName())), IscPerson::getPersonName, iscPersonReq.getPersonName())
                .orderByDesc(IscPerson::getCreateTime)
                .page(page)
                ;

        IPage<IscPersonDTO> iscPersonDTOIPage = IPageUtil.trans(iscPersonList);

        return iscPersonDTOIPage;
    }

    @Transactional
    public Integer synPerson() {
        Integer synNumber = 0;

        // 查询需要同步的数据量
        UserReqISC userReqISC = new UserReqISC();
        userReqISC.setPageNo(1);
        userReqISC.setPageSize(1);

        JSONObject jsonObject = (JSONObject) artemisPostUtil.callPostApi("/api/resource/v2/person/advance/personList", userReqISC);

        // 需要同步的总数
        Integer total = jsonObject.getInteger("total");

        LocalDateTime now = LocalDateTime.now();

        if (total == null) {
            return synNumber;
        }
        //删除数据
        //personMapper.deleteAll(); // 2019.10.21 注释，手动添加不存在的人员

        // 先删除表再插入, 20241217
        this.remove(null);

        // 分页量
        Integer pageSize = 1000;
        // 页数计算
        Integer pageCount = (total / pageSize) + 1;


        for (int i = 1; i <= pageCount; i++) {

            userReqISC.setPageSize(pageSize);
            userReqISC.setPageNo(i);
            JSONObject json = (JSONObject) artemisPostUtil.callPostApi("/api/resource/v2/person/advance/personList", userReqISC);
            JSONArray jsonArray = json.getJSONArray("list");
            List<IscPerson> personList = JSONObject.parseArray(jsonArray.toJSONString(),
                    IscPerson.class);

            int j = 1;
            for (IscPerson person : personList) {
                // 保存
                try {
                    person.setFalshTime(now);

                    this.getBaseMapper().synPerson(person);
                } catch (Exception e) {
                    log.debug(e.getMessage());
                    total = total - 1;
                }
                log.debug("第" + i + "组,第" + j + "个");
                j++;
            }
        }

        log.debug("同步用户的总数： " + jsonObject.getInteger("total"));
        log.debug("同步用户的实际总数： " + total);
        return total;
    }

    public static void main(String[] args) {
        String jsonStr = "{\"code\":\"0\",\"msg\":\"success\",\"data\":{\"total\":134,\"pageNo\":1,\"pageSize\":1,\"list\":[{\"personId\":\"ce641b4014714ddda510c52fee01ca14\",\"personName\":\"韦生荣\",\"gender\":1,\"certificateType\":0,\"jobNo\":\"1022\",\"age\":0,\"marriaged\":0,\"lodge\":0,\"syncFlag\":0,\"pinyin\":\"weishengrong\",\"createTime\":\"2021-12-24T14:13:00.877+08:00\",\"updateTime\":\"2022-01-12T13:08:33.546+08:00\",\"faceNum\":1,\"orgIndexCode\":\"root000000\",\"orgName\":\"默认组织\",\"orgPath\":\"@root000000@\",\"orgPathName\":\"默认组织\",\"personPhoto\":[{\"serverIndexCode\":\"d68b3d97-e0d5-4c55-858a-b7670434d0a6\",\"personPhotoIndexCode\":\"4cac4a18-3660-4373-a415-34058de16280\",\"picUri\":\"/pic?dd00=8c01la7-do611b*o3c5=2187*3l2037244186*4tp===111***sb2=65512877956eb--*4ce5=pi18fo=0-560080\"}]}]}}";
        Feature[] features = {Feature.AllowISO8601DateFormat};
        JSONObject json = JSONObject.parseObject(jsonStr, features);
        JSONArray jsonArray = json.getJSONObject("data").getJSONArray("list");

        List<IscPerson> personList = JSONObject.parseArray(jsonArray.toJSONString(), IscPerson.class);

        System.out.println(personList);
    }
}
